package com.supor.aiot.common.push;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;

import com.alipay.pushsdk.content.AliPushRcvService;
import com.alipay.pushsdk.data.BDataBean;
import com.alipay.pushsdk.push.PushAppInfo;
import com.android.baseconfig.common.helper.ActivityManager;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.mpaas.mps.adapter.api.MPPush;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.helper.GlobalDataCache;

import org.json.JSONException;
import org.json.JSONObject;

import alipay.yunpushcore.rpc.ResultPbPB;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

/**
 * Created by larry.cl.
 * push的接收服务
 */
public class PushMsgService extends AliPushRcvService {

    private static final String TAG = "lllll-pushTag";
    //推送消息的类型，用户自定义即可
    public static final int TYPE_MSG = -1;
    //自建渠道推送标识
    public static String mAdToken = "";
    //第三方渠道推送标识
    public static String mThirdToken = "";

    public static int platformType = 0;

    public static boolean useDefault = false;

    public PushMsgService() {
        super();
    }

    /**
     * 判断展示类消息是否使用内建通知。
     * 返回true，则所有展示类（非静默）消息由mPaaS进行处理，handleActionReceived不再被调用。
     * 如果是静默类还是会都handleActionReceived。
     * 返回false，表示透传所有消息。
     */
    @Override
    protected boolean useDefaultNotification(String msgKey, String msgValue) {
        Logc.i(TAG,
                "msgKey = " + msgKey + ", msgValue = " + msgValue + ", useDefault = " + useDefault);
        return useDefault;
    }

    /**
     * This is only called when useDefaultNotification returns false.
     * 消息处理回调，自建消息需要接入方自行处理弹出通知等工作。
     *
     * @param msgKey   消息推送的key
     * @param msgValue 消息推送的value
     * @param clicked  是否已经点击了
     *                 对于三方渠道来说clicked = true ,展示通知栏
     *                 对于自建渠道来说clicked = false，没有展示通知栏
     */
    @Override
    protected void handleActionReceived(String msgKey, String msgValue, boolean clicked) {
        Logc.i(TAG, "msgKey = " + msgKey + ", msgValue = " + msgValue + ", clicked = " + clicked);
        if (TextUtils.isEmpty(msgValue)) {
            return;
        }
        BDataBean data = BDataBean.create(msgValue);
        if (clicked) {
            startMain();
            return;
        }
        // 非静默消息弹系统框
        if (!data.isSilent()) {
            // show your notification and handle action
            NotificationHelper helper = new NotificationHelper(getApplicationContext());
            helper.notify(data.getTitle(), data.getContent());
        } else {
            // "params":{"ALIMpsTaskId":"313288998","ALIMpsChannel":"ANDROID",
            // "eventType":"user_cancellation","ALIMpsPushType":"SIMPLE"}
            String params = data.getParams();
            try {
                JSONObject object = new JSONObject(params);
                String eventType = object.getString(Constants.Key.EVENT_TYPE);
                // 用户注销
                if (Constants.Value.USER_CANCELLATION.equalsIgnoreCase(eventType)) {
                    Intent intent = new Intent(Constants.PUSH_SERVICE_ACTION);
                    intent.putExtra(Constants.Key.PUSH_TYPE, TYPE_MSG);
                    intent.putExtra(Constants.Key.PUSH_KEY, msgKey);
                    intent.putExtra(Constants.Key.PUSH_VALUE, msgValue);
                    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
                    if (startMain()) {
                        // 如果是触碰拉起APP，则先把注销标志置为true，在获取NFC参数时在上报注销
                        // if (DataCache.NFC_PARAMS != null) {
                        //     DataCache.NEED_CLOSE_ACCOUNT = true;
                        // } else {
                            // AppAgent.getApp().mainHandler.postDelayed(()
                            //         -> SuporPresenter.getInstance().reportCloseAccount(1), 5000);
                        // }
                    } else {
                        // SuporPresenter.getInstance().reportCloseAccount(1);
                    }
                } else if (Constants.Value.USER_BIND_PUSH.equalsIgnoreCase(eventType)) {
                    // 用户绑定操作
                    Activity activity = ActivityManager.getActivity(0);
                    GlobalDataCache.getBindDevice();
                    Logc.i("bottom activity: " + (activity == null ? "null" : activity.getClass().getName()));
                    // if (activity instanceof MainActivity) {
                    //     // SuporPresenter.getInstance().reportBindStatus(1);
                    // }
                } else if (Constants.Value.USER_UNBIND_PUSH.equalsIgnoreCase(eventType)) {
                    // 用户解绑操作
                    Activity activity = ActivityManager.getActivity(0);
                    Logc.i("bottom activity: " + (activity == null ? "null" : activity.getClass().getName()));
                    // if (activity instanceof MainActivity) {
                    //     // SuporPresenter.getInstance().reportBindStatus(2);
                    // }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean startMain() {
        try {
            Activity activity = ActivityManager.getActivity(0);
            Logc.i("bottom activity: " + (activity == null ? "null" : activity.getClass().getName()));
            if (activity != null && !("MainActivity".equalsIgnoreCase(activity.getClass().getSimpleName()))) {
                SuporPresenter.getInstance().startMain(activity);
                return true;
            }
        } catch (Exception e) {
            Logc.e(TAG, "Unable start main activity", e);
        }
        return false;
    }

    /**
     * @param adToken 自建渠道的推送标识
     */
    @Override
    protected void handleActionId(String adToken) {
        Logc.i(TAG, "adToken " + adToken);
        PushAppInfo pushAppInfo = new PushAppInfo(getApplicationContext());
        pushAppInfo.setAppToken(adToken);
        // LoggerFactory.getTraceLogger().debug(TAG, "自建渠道的adToken: " + adToken);
        // Intent intent = new Intent(PUSH_SERVICE_ACTION);
        // intent.putExtra("push_type", TYPE_INNER_PUSH_INIT);
        // intent.putExtra("push_token", adToken);
        // LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        mAdToken = adToken;
        bindUser();
        uploadThridToken();
    }

    /**
     * @param thirdToken   三方渠道的推送标识
     * @param platformType 三方渠道的类型 华为=5 小米=4
     */
    @Override
    protected void handleActionThirdId(String thirdToken, int platformType) {
        Logc.i(TAG, "thirdToken = " + thirdToken + ", platformType = " + platformType);
        // LoggerFactory.getTraceLogger().debug(TAG, "第三方渠道的adToken: " + thirdToken + "platformType:" +
        //         " " + platformType);
        // Intent intent = new Intent(PUSH_SERVICE_ACTION);
        // intent.putExtra("push_type", TYPE_THIRD_PUSH_INIT);
        // intent.putExtra("push_thirdToken", thirdToken);
        // intent.putExtra("push_channel", platformType);
        // LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        mThirdToken = thirdToken;
        PushMsgService.platformType = platformType;
        uploadThridToken();
    }

    /**
     * 绑定用户，目前是绑定手机唯一标识
     */
    public static void bindUser() {
        ThreadUtils.execute(() -> {
            // MPPush.setBadgeActivityClassName(this, NotificationActivity.class.getName());
            // 此处的用户 userId 不一定为开发者用户系统的真实标识，但是一定是可以与用户形成一一映射关系。
            // 参数 userId，adtoken（会在 service handleActionId 中接收到）
            if (!TextUtils.isEmpty(PushMsgService.mAdToken) && GlobalDataCache.uniqueId != null) {
                try {
                    ResultPbPB resultBean = MPPush.bind(AppAgent.getApp(),
                            GlobalDataCache.uniqueId, PushMsgService.mAdToken);
                    handlePbPBResult("bind user", resultBean);
                } catch (Exception e) {
                    e.printStackTrace();
                    Logc.e("bindUser: " + e.getMessage());
                }

            } else {
                Logc.e("mAdToken or unique is null");
            }
        });

    }

    /**
     * 解绑用户，不接收推送
     */
    public static void unbindUser() {
        ThreadUtils.execute(() -> {
            // MPPush.setBadgeActivityClassName(this, NotificationActivity.class.getName());
            // 此处的用户 userId 不一定为开发者用户系统的真实标识，但是一定是可以与用户形成一一映射关系。
            // 参数 userId，adtoken（会在 service handleActionId 中接收到）
            if (!TextUtils.isEmpty(PushMsgService.mAdToken) && GlobalDataCache.uniqueId != null) {
                try {
                    ResultPbPB resultBean = MPPush.unbind(AppAgent.getApp(),
                            GlobalDataCache.uniqueId, PushMsgService.mAdToken);
                    handlePbPBResult("unbind user", resultBean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Logc.e("doUnBind: mAdToken is null");
            }
        });
    }

    //第三方push标识的上报接口（封装后的简易接口）
    public static void uploadThridToken() {
        ThreadUtils.execute(() -> {
            try {
                if (!TextUtils.isEmpty(PushMsgService.mAdToken) && !TextUtils.isEmpty(PushMsgService.mThirdToken)) {
                    final ResultPbPB resultPbPB = MPPush.report(AppAgent.getApp(),
                            PushMsgService.mAdToken
                            /*channel可以选择XIAOMI,HUAWEI和GCM*/
                            , PushMsgService.platformType, PushMsgService.mThirdToken);
                    handlePbPBResult("third push token report", resultPbPB);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }

    private static void handlePbPBResult(final String operationType, final ResultPbPB resultPbPB) {
        StringBuilder sb = new StringBuilder();
        if (resultPbPB.success) {
            sb.append(operationType).append(" ").append("success").append("\n");
        } else {
            sb.append(operationType).append(" ").append("failed, ").append(resultPbPB.message).append("\n");
        }
        sb.append(resultPbPB.toString());
        Logc.i(sb.toString());
    }
}
